<template>
  <div>
    <div class="app-title">
      <span>职务配置</span>
    </div>
    <!-- 按钮 -->
    <div class="filter-container">
      <div>
        <el-col style="text-align:right;margin-top: -8px;">
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px;"
            type="primary"
            @click="handleHookUp"
          >
            挂接
          </el-button>
        </el-col>
      </div>
    </div>
    <!-- 表格部分 -->
    <el-table
      ref="singalTable"
      v-loading="listLoading"
      :height="tableHeight"
      :data="list"
      :stripe="true"
      fit
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
    >
      <template slot="empty">
        <tableEmpty />
      </template>
      <el-table-column type="selection" align="center" width="50" />
      <el-table-column type="index" align="center" width="50" label="序号" />

      <el-table-column label="人员类别" align="center">
        <template slot-scope="{row}">
          <span>{{ row.personTypeCode+'-'+row.personTypeName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="职务" align="center">
        <template slot-scope="{row}">
          <span>{{ row.postCode+'-'+row.postName }}</span>
        </template>
      </el-table-column>

    </el-table>
    <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <!-- 新增/编辑页面部分 -->
    <el-dialog  v-dialogDrag  
      :close-on-click-modal="false"
      title="挂接"
      :visible.sync="dialogFormVisible"
      style="padding: 0px"
      width="50%"
    >
      <el-form
        ref="dataForm"
        class="dialog-Backgroundcolor"
        :model="listQuery"
        label-position="right"
        label-width="100px"
      >
        <el-row>
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px; float: right"
            type="primary"
            @click="handleAdd"
          >
            新增
          </el-button>
          <el-button
            size="small"
            class="filter-item"
            style="margin-left: 10px; float: right"
            type="primary"
            :loading="saveLoading"
            @click="handleSave"
          >
            保存
          </el-button>
        </el-row>
        <el-table
          ref="singalEditTable"
          v-loading="editTableListLoading"
          max-height="400"
          :data="editListData"
          :stripe="true"
          fit
          class="editTable"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <template slot="empty">
            <tableEmpty />
          </template>
          <el-table-column type="selection" align="center" width="55" />
          <el-table-column type="index" align="center" width="80" label="序号" />
          <el-table-column label="职务" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.id" placeholder="请选择">
                <el-option
                  v-for="item in allPostLists"
                  :key="item.id"
                  :label="item.code+'-'+item.name"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { querySalPostAll, querySalPersonPostRefPage, saveSalPersonPostRef, querySalPostByPersonTypeId } from '@/api/salaryConfigManage/personTypePostConfig'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import tableEmpty from '@/components/table/empty'
export default {
  name: 'PersonTypePostHookUpChildren',
  components: { Pagination, tableEmpty },
  filters: {
  },
  data() {
    return {
      tableHeight: null,
      that: this,
      list: null,
      total: 0,
      listLoading: false,
      saveLoading: false,
      listQuery: {
        page: 1,
        limit: 200
      },
      formData: {
        personTypeId: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      editTableListLoading: false,
      editListData: [],
      addItem: {
        postId: '',
        isNewItem: ''
      },
      allPostLists: []
    }
  },
  watch: {
    // 表格的数据数组
    list(val) {
      this.doLayout()
    }
  },
  created() {
    this.getList()
    this.initBaseData()
  },
  mounted() {
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  methods: {
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 220
    },
    getList() {
      this.listLoading = true
      querySalPersonPostRefPage(this.listQuery).then((response) => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 挂接
    handleHookUp() {
      const selection = this.$refs.singalTable.selection
      if (selection.length !== 1) {
        this.$message({
          showClose: true,
          message: '请选择要挂接的数据',
          type: 'warning',
          duration: 4000
        })
        return
      }
      this.dialogStatus = '挂接'
      this.dialogFormVisible = true
      this.formData.personTypeId = selection[0].personTypeId
      this.editTableListLoading = true
      const params = { 'personTypeId': selection[0].personTypeId }
      querySalPostByPersonTypeId(params).then((response) => {
        this.editListData = response.data
        this.editTableListLoading = false
      })
    },
    handleAdd() {
      const addItem = { ...this.addItem }
      addItem.isNewItem = Math.random()
        .toString(16)
        .substr(2, 8)
      this.editListData.unshift(addItem)
    },
    // 保存
    handleSave() {
      if (this.editListData.length === 0) {
        this.$message({
          showClose: true,
          message: '请先新增职务后，再保存',
          type: 'warning',
          duration: 4000
        })
        return
      }
      this.saveLoading = true
      const postIds = []
      const editListTableData = this.unique()
      editListTableData.forEach(item => {
        postIds.push(item.id)
      })
      this.formData['id'] = this.formData.personTypeId
      this.formData['salPostList'] = postIds
      saveSalPersonPostRef(this.formData).then((response) => {
        this.dialogFormVisible = false
        this.$message({
          showClose: true,
          message: '保存成功',
          type: 'success',
          duration: 4000
        })
        this.saveLoading = false
        this.handleFilter()
      }).catch(() => {
        this.saveLoading = false
      })
    },
    unique() {
      const editListData = this.editListData
      const res = new Map()
      return editListData.filter(editData =>
        !res.has(editData.id) &&
        res.set(editData.id)
      )
    },
    // 删除
    handleDelete(row) {
      const index = this.editListData.indexOf(row)
      this.editListData.splice(index, 1)
    },
    // 初始化数据
    initBaseData() {
      querySalPostAll().then((response) => {
        this.allPostLists = Object.assign({}, response.data)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.formDeviation {
  margin-left: 18%;
  .el-form-item__error {
    padding-top: 5%;
  }
}
.redstar.el-form-item__error{
  margin-top: 35px !important;
  left: -96px !important;
}
</style>
